﻿using System.ComponentModel;

namespace LvcChong
{
    public partial class FormUserQuery : Form
    {
        private BindingList<UserInfoOutput> _source = new BindingList<UserInfoOutput>();
        private LayerHelper _layerHelper = new LayerHelper();

        public FormUserQuery()
        {
            InitializeComponent();
            pager.OnPageChanged += Pagination_OnPageChanged;
            pager.OnPageSizeChanged += Pager_OnPageSizeChanged;

            InitGridLayout();

            InitData();
        }

        private void Pager_OnPageSizeChanged(object? sender, EventArgs e)
        {
            pager.Tag = null;
        }

        public FormUserQuery(string userId) : this()
        {
            txtValue.Text = userId;
        }

        private void Pagination_OnPageChanged(object? sender, EventArgs e)
        {
            RefreshData();
        }

        private void InitGridLayout()
        {
            grid.InitializeRow += (s, e) =>
            {
                var item = e.Row.ListObject as UserInfoOutput;
                if (item == null) return;

                if (item.inTime.ParseToLong(0) != 0)
                {
                    var time = item.inTime.ParseToLong().ToDateTimeFromMilliseconds();
                    if (time != null)
                        e.Row.Cells[nameof(OrderQueryOutput.inTime)].Value = time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                }
            };

            grid.ClickCell += (s, e) =>
            {
                if (e.Cell.Column.Key == nameof(OrderQueryOutput.id))
                {
                    new FormVehicleQuery(e.Cell.Value.ToString(), ValueType.UserID).ShowDialog();
                }
            };

            var displayCol = new List<UltraGridDisplayItem> {
                new UltraGridDisplayItem{ Key=nameof(UserInfoOutput.id), Caption="用户编号", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(UserInfoOutput.userName), Caption="用户名称", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(UserInfoOutput.level), Caption="用户等级", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(UserInfoOutput.phone), Caption="手机号", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(UserInfoOutput.inTime), Caption="创建时间", Position=2,ColumnWidth =180},
            };

            grid.SetDataBinding(_source, null);
            UltraGridHelper.InitializeUltraGridDisplay(grid, displayCol, true, new UltraGridOptions
            {
                EnableFixedHeader = true,
                EnableExport = true,
                ShowSummary = true,
                EnableFilter = true,
            });

            grid.DisplayLayout.NoDataSourceMessageEnabled = Infragistics.Win.DefaultableBoolean.False;
            grid.DisplayLayout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;

            grid.DisplayLayout.Override.RowAlternateAppearance.BackColor = Color.FromArgb(244, 244, 244);

            grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.id)].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.URL;
        }

        private void InitData()
        {
            cboQueryType.SetDataSource(typeof(QueryType).EnumToNameValues(), "Caption");
            cboQueryType.SelectedIndex = 0;
            dtStart.Value = DateTime.Now.GetFirstDayOfMonth();
            dtEnd.Value = DateTime.Now.GetLastDayOfMonth();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private async void RefreshData()
        {
            var ret = await LayerRefreshAsync(() => GlobalContext.DataProvider.UserListQuery(new UserListInput
            {
                page = pager.CurrentPageNo,
                limit = pager.PageSize,
                fromPage = pager.CurrentPageNo - 1 <= 0 ? null : pager.CurrentPageNo - 1,
                leastTotal = pager.TotalRecords == 0 ? null : pager.TotalRecords,
                deepPageTokenArr = pager.Tag?.ToString(),
                queryType = cboQueryType.SelectedItem == null ? 1 : (int)((QueryType)cboQueryType.SelectedItem.DataValue),
                queryValue = txtValue.Text,
                dateRange = $"{dtStart.DateTime.ToString("yyyy-MM-01")} ~ {dtEnd.DateTime.ToString("yyyy-MM-dd")}"
            }));
            _source.Clear();
            if (ret != null && ret.Data != null)
            {
                if (pager.Tag == null)
                    pager.Tag = ret.OtherMap?.deepPageToken;
                else pager.Tag = pager.Tag + "," + ret.OtherMap?.deepPageToken;
                pager.RefreshPageData(ret.Count);
                foreach (var item in ret.Data) _source.Add(item);
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            cboQueryType.SelectedIndex = 0;
            txtValue.Clear();
            dtStart.Value = DateTime.Now.GetFirstDayOfMonth();
            dtEnd.Value = DateTime.Now.GetLastDayOfMonth();
        }

        private Task<T> LayerRefreshAsync<T>(Func<T> action)
        {
            var ret = Task.Run(() =>
            {
                try
                {
                    plQuery.UpdateUI(() => plQuery.Enabled = false);
                    _layerHelper.ShowOpaqueLayer(plGrid, 30);
                    return action();
                }
                finally
                {
                    _layerHelper.HideOpaqueLayer();
                    plQuery.UpdateUI(() => plQuery.Enabled = true);
                }
            });
            return ret;
        }
    }
}